package com.example.springpostbody.core;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CustomRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] cachedBody;  // 缓存请求体字节数组
    private final Charset charset;    // 缓存字符集

    public CustomRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 获取请求的字符编码，如果没有则使用UTF-8
        String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding() : StandardCharsets.UTF_8.name();
        this.charset = Charset.forName(encoding);

        // 缓存请求体字节
        //cachedBody = request.getInputStream().readAllBytes();
        cachedBody = StreamUtils.copyToByteArray(request.getInputStream());
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 返回缓存的字节数组的输入流
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cachedBody);
        return getServletInputStream(byteArrayInputStream);
    }

    public static ServletInputStream getServletInputStream(ByteArrayInputStream byteArrayInputStream) {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {}

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    // 获取请求体的字符串表示
    public String getBody() {
        return new String(cachedBody, charset);
    }
}

